﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using MacViet.DataBaseAPI;

[AjaxPro.AjaxNamespace("Ajax_Control_Appointment_app")]
public partial class Control_UCAppointPopUp : System.Web.UI.UserControl
{
    private static int acc_id = 0;
    private static int app_id = 156;
    private APPOINTMENTSDataAPI app = new APPOINTMENTSDataAPI();
    private SERVICE_CATEGROIESDataAPI cate = new SERVICE_CATEGROIESDataAPI();
    private SERVICESDataAPI ser = new SERVICESDataAPI();
    private CLIENTSDataAPI cl = new CLIENTSDataAPI();

    private const string STATUS = "WAIT";
    public DataTable dtResult = new DataTable();
    private MyResult result = new MyResult();
    public DataTable dtRes = new DataTable();
    private string acc_email = string.Empty;
    PRODUCTSDataAPI product = new PRODUCTSDataAPI();
    APPOINTMENTSDataAPI appmore = new APPOINTMENTSDataAPI();
    BILLDataAPI BILL = new BILLDataAPI();

    private int CountRow = 0;

    protected void Page_Load(object sender, EventArgs e)
    {
        //btnSave.Attributes.Add("OnClick", "return SaveClick(this);");
        if (!IsPostBack)
        {
            AjaxPro.Utility.RegisterTypeForAjax(typeof(Control_UCAppointPopUp));
            if (Session["acc_id"] != null)
                acc_id = int.Parse(Session["acc_id"].ToString());
            if (Request.QueryString["APP_ID"] != null && Request.QueryString["APP_ID"].ToString() != string.Empty)
                app_id = int.Parse(Request.QueryString["APP_ID"].ToString());
            DataTable dtapp = appmore.getBy_APP_ID(app_id, acc_id);

            txtDateApp.Text = DateTime.Now.ToShortDateString();
            LoadData(acc_id);
            loadService(app_id);
            loadService2(acc_id);
            LoadPayment();

        }

    }
    [AjaxPro.AjaxMethod]
    public MyResult loadServiceBySerTypeId(string value, string SerID)
    {
        MyResult My = new MyResult();
        DataTable dtser = ser.getBySER_ID(Convert.ToInt32(value), acc_id);
        My.tbl = dtser;
        My.SerID = SerID;
        return My;

        //dt = cate.getBySERCATE_ID(Convert.ToInt32(id));
        //return dt;
    }

    [AjaxPro.AjaxMethod]
    public MyResult LoadServicePrice(string val, string PriceID)
    {
        MyResult result = new MyResult();
        DataTable get = ser.getServices_Price(Convert.ToInt32(val), acc_id);
        result.tbl = get;
        result.PriceID = PriceID;
        return result;
    }

    [AjaxPro.AjaxMethod]
    public MyResult LoadProduct(string value, string proId)
    {
        MyResult res = new MyResult();
        DataTable pro = product.getProName_ByPROTYP_ID(Convert.ToInt32(value), acc_id);
        res.tbl = pro;
        res.proId = proId;
        return res;
    }
    [AjaxPro.AjaxMethod]
    public MyResult LoadDescription(string val, string DesID, string PriceID)
    {
        MyResult result = new MyResult();
        DataTable Des = product.Get_DESCRIPTION(Convert.ToInt32(val), acc_id);
        result.tbl = Des;
        result.DesID = DesID;
        result.PriceID = PriceID;
        return result;
    }

    private void LoadPayment()
    {
        try
        {
            PAYMENT_TYPEDataAPI payment = new PAYMENT_TYPEDataAPI();
            DataTable dt = payment.getPaymentType(acc_id);
            ddlPaymentApp.DataSource = dt;
            ddlPaymentApp.DataTextField = "PTYP_NAME";
            ddlPaymentApp.DataValueField = "PTYP_ID";
            ddlPaymentApp.DataBind();
            ddlPaymentApp.Items.Insert(0, new ListItem("-Choose Payment Type-", "0"));
        }
        catch (Exception ex)
        {
            ex.ToString();
        }
    }
    protected void txtCash_TextChanged(object sender, EventArgs e)
    {
        CheckChange();
    }
    private void CheckChange()
    {
        try
        {
            if (txtCashApp.Text == "")
            {
                txtCashApp.Text = "0";
            }
            else
            {
                double cash = double.Parse(txtCashApp.Text);
                float total = float.Parse(txtTotalApp.Text);
                if (cash >= total)
                {
                    double Change = cash - total;
                    txtChangeApp.Text = Change.ToString();
                    lblCashCheckApp.Text = "";


                }
                else if (cash != 0)
                {
                    lblCashCheckApp.Text = "Your Cash must be greater or equal total ";
                    lblCashCheckApp.Visible = true;
                    txtCashApp.Text = "";

                    txtChangeApp.Text = "";
                }
            }
        }
        catch (Exception ex)
        {
            ex.ToString();
        }
    }

    [AjaxPro.AjaxMethod]
    public string LoadDataInsert(string ProID, string More, string ProName, string Price, string Quantity, string Amount, string SerName, string SerPrice, string Tips, string ser_id, string flag)
    {
        try
        {

            string[] strQuantity = Quantity.Split(',');
            DateTime Date = DateTime.Now;
            string testQuan = strQuantity[0].ToString();
            if (testQuan != "")
            {

                string[] strProId = ProID.Split(',');
                string[] strProName = ProName.Split(',');
                string[] strPrice = Price.Split(',');

                string[] strAmount = Amount.Split(',');
                string[] strMore = More.Split(',');

                int ID = 1;
                DataTable top = BILL.getTopBIll_Detail(acc_id);
                if (top != null)
                    ID = int.Parse(top.Rows[0]["BIL_DETAIL_ID"].ToString()) + 1;
                double Total = 0;
                for (int i = 0; i < strQuantity.Length; i++)
                {
                    //-----------------------------Update Quantity-------------------------------------------------------------------
                    int PrId = int.Parse(strProId[i]);
                    string PrName = strProName[i].ToString();
                    double Amou = Math.Round(float.Parse(strAmount[i]), 2);


                    string PaymentType = strMore[1].ToString();
                    switch (PaymentType)
                    {
                        case "2":
                            PaymentType = "VISA";
                            break;
                        case "3":
                            PaymentType = "Credit Card";
                            break;
                        case "4":
                            PaymentType = "Master Card";
                            break;
                        default:
                            PaymentType = "Cash";
                            break;
                    }
                    string Cus = strMore[0].ToString();
                    int qt = int.Parse(strQuantity[i]);

                    PRODUCTSDataAPI pro = new PRODUCTSDataAPI();
                    pro.updatePro_two(PrId, qt);
                    //-----------------------------Update Quantity-------------------------------------------------------------------

                    //-----------------------------Insert To BIll_Detail-------------------------------------------------------------------

                    //BILL.InsertAllToBill_DETAIL(ID, name, total, date, paytype, proname, quantity, acc_id);
                    BILL.InsertAllToBill_DETAIL(ID, Cus, Amou, Date, PaymentType, PrName, qt, acc_id);
                    Total += Amou;
                }
                //-----------------------------Insert To BIll-------------------------------------------------------------------
                BILL.Insert_Bill_End(ID, Total, acc_id, app_id);
                //------------------------------------------------------------------------------------------------
            }
            int IDSer = 1;
            DataTable topsER = BILL.getTopBIll_Ser_Detail(acc_id);
            if (topsER != null)
                IDSer = int.Parse(topsER.Rows[0]["BILL_SER_ID"].ToString()) + 1;
            string[] strSerName = SerName.Split(',');            
            string[] strSerPrice = SerPrice.Split(',');
            string[] strServiceID = ser_id.Split(',');              
            dtResult = appmore.getOnlyIdByAppID(acc_id, app_id);
            int empid = int.Parse(dtResult.Rows[0]["EMP_ID"].ToString());
            int cliid = int.Parse(dtResult.Rows[0]["CLI_ID"].ToString());
            int spaid = int.Parse(dtResult.Rows[0]["SPA_ID"].ToString());
            string appstatus=dtResult.Rows[0]["APP_STATUS"].ToString();
            
            APPOINTMENTSDataAPI apphet = new APPOINTMENTSDataAPI();
            if (strSerPrice[0].ToString() != "")//trong truong hop App_id chon them dich vu.                
            {
                for (int i = 0; i < strSerPrice.Length; i++)
                {
                    int SerViceId = int.Parse(strServiceID[i].ToString());
                    appmore.insertAPPOINTMENT_SERVICES(app_id, SerViceId, appstatus);
                    if (flag == "Pay")
                    {
                        dtResult = app.getBy_APP_ID(app_id, acc_id);
                        for (int j = 0; j < dtResult.Rows.Count; j++)
                        {                            
                            string ServiceName = dtResult.Rows[j]["SER_NAME"].ToString();
                            double ServicePrice = double.Parse(dtResult.Rows[j]["SER_PRICE"].ToString());
                            BILL.InsertToBill_SER_DETAIL(app_id, acc_id, IDSer, ServiceName, ServicePrice, Date, empid);
                        }
                    }
                }
            }
            else //trong truong hop App_id khong chon them dich vu.
            {
                if (flag == "Pay")
                {
                    dtResult = app.getBy_APP_ID(app_id, acc_id);
                    for (int i = 0; i < dtResult.Rows.Count; i++)
                    {
                        //int SerViceId = int.Parse(dtResult.Rows[i]["SER_ID"].ToString());
                        string ServiceName = dtResult.Rows[i]["SER_NAME"].ToString();
                        double ServicePrice = double.Parse(dtResult.Rows[i]["SER_PRICE"].ToString());                      
                        BILL.InsertToBill_SER_DETAIL(app_id, acc_id, IDSer, ServiceName, ServicePrice, Date, empid);                        
                    }
                }
            }
  
            if (flag == "Pay")
            {
                if (Tips == "")
                {
                    Tips = "0";
                }
                BILL.Insert_Bill_SER_End(IDSer, float.Parse(Tips), acc_id);
                apphet.UpdateStatusDone(app_id, acc_id);
            }
            else
            {
                apphet.UpdateStatusWait_Doing(app_id, acc_id);
            }

        }
        catch (Exception ex)
        {
            ex.ToString();
        }        
        return More;        
    }
    private void LoadData(int acc_id)
    {
        PRODUCT_TYPESDataAPI product_type = new PRODUCT_TYPESDataAPI();
        DataTable dt = product_type.getAll(acc_id);
        grvShowBillAPP.DataSource = dt;
        grvShowBillAPP.DataBind();
    }

    private void loadService(int app_id)
    {
        dtResult = app.getBy_APP_ID(app_id, acc_id);
        if (dtResult != null)
        {
            if (dtResult.Rows.Count != 0)
            {
                CountRow = dtResult.Rows.Count;
                float SubTotal = 0;
                for (int i = 0; i < dtResult.Rows.Count; i++)
                {
                    SubTotal += float.Parse(dtResult.Rows[i]["SER_PRICE"].ToString());
                }
                txtSubApp.Text = "$ " + SubTotal;
                txtCusNameApp.Text = dtResult.Rows[0]["CLI_NAME"].ToString();
                txtCusNameApp.ReadOnly = true;
                txtPhoneapp.Text = dtResult.Rows[0]["CLI_PHONE"].ToString();
                txtCusNameApp.ReadOnly = true;
                GrvService.DataSource = dtResult;
                GrvService.DataBind();
            }
        }
    }
    private void loadService2(int acc_id)
    {
        dtResult = cate.getByACC_ID(acc_id);
        GrvService2.DataSource = dtResult;
        GrvService2.DataBind();
    }
    protected void grvShowBillAPP_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            DropDownList ddlProTypApp = e.Row.FindControl("ddlProTypApp") as DropDownList;
            DropDownList ddlProApp = e.Row.FindControl("ddlProApp") as DropDownList;

            Label lblDesApp = e.Row.FindControl("lblDesApp") as Label;
            Label lblPriceApp = e.Row.FindControl("lblPriceApp") as Label;
            TextBox txtQuantityApp = e.Row.FindControl("txtQuantityApp") as TextBox;
            Label lblAmountApp = e.Row.FindControl("lblAmountApp") as Label;
            PRODUCT_TYPESDataAPI product_type = new PRODUCT_TYPESDataAPI();
            DataTable dt = product_type.getAll(acc_id);
            ddlProTypApp.DataSource = dt;
            ddlProTypApp.DataTextField = "PROTYP_NAME";
            ddlProTypApp.DataValueField = "PROTYP_ID";
            ddlProTypApp.DataBind();
            ddlProTypApp.Items.Insert(0, new ListItem("-Choose Item-", "0"));
            ddlProTypApp.Attributes.Add("onChange", "return proTypeChange('" + ddlProApp.ClientID + "',this);");
            ddlProApp.Attributes.Add("onChange", "return ProductChange('" + ddlProApp.ClientID + "','" + lblDesApp.ClientID + "','" + lblPriceApp.ClientID + "','" + lblAmountApp.ClientID + "','" + txtQuantityApp.ClientID + "',this);");

            ddlProApp.Attributes.Add("onClick", "return ProductClick(this);");
            txtQuantityApp.Attributes.Add("onChange", "return QuantityChange('" + txtQuantityApp.ClientID + "','" + lblPriceApp.ClientID + "','" + lblAmountApp.ClientID + "','" + lblDesApp.ClientID + "',this);");
            txtQuantityApp.Attributes.Add("onClick", "return QuantityClick('" + lblAmountApp.ClientID + "',this);");
            txtTaxApp.Attributes.Add("onChange", "return txtTaxChange(this);");
            txtCashApp.Attributes.Add("onChange", "return CashChange('" + txtCashApp.ClientID + "','" + ddlPaymentApp.ClientID + "',this);");
            ddlPaymentApp.Attributes.Add("onChange", "return PaymentChange(this);");
            //string id=hdfId.Value.ToString();
            //btnCheckOut.Attributes.Add("onClick", "return showdivSale('"+id+"',this);");

        }
    }
    protected void GrvService_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        Label lblSertype = e.Row.FindControl("lblSertype") as Label;
        Label lblSerName = e.Row.FindControl("lblSerName") as Label;
        Label lblPriceService = e.Row.FindControl("lblPriceService") as Label;

    }
    protected void GrvService2_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            DropDownList ddlServiceType2 = e.Row.FindControl("ddlServiceType2") as DropDownList;
            DropDownList ddlService2 = e.Row.FindControl("ddlService2") as DropDownList;
            Label lblPriceService2 = e.Row.FindControl("lblPriceService2") as Label;

            dtRes = cate.getByACC_ID(acc_id);
            ddlServiceType2.DataSource = dtRes;
            ddlServiceType2.DataTextField = "SERCAT_NAME";
            ddlServiceType2.DataValueField = "SERCAT_ID";
            ddlServiceType2.DataBind();


            ddlServiceType2.Items.Insert(0, new ListItem("-Choose Item-", "0"));


            ddlServiceType2.Attributes.Add("onChange", "return ServiceTypeChange('" + ddlService2.ClientID + "',this);");
            ddlService2.Attributes.Add("onChange", "return ServiceChange('" + ddlService2.ClientID + "','" + lblPriceService2.ClientID + "',this);");

            //ddlProApp.Attributes.Add("onClick", "return ProductClick(this);");
            //txtQuantityApp.Attributes.Add("onChange", "return QuantityChange('" + txtQuantityApp.ClientID + "','" + lblPriceApp.ClientID + "','" + lblAmountApp.ClientID + "',this);");
            //txtQuantityApp.Attributes.Add("onClick", "return QuantityClick('" + lblAmountApp.ClientID + "',this);");
            //txtTaxApp.Attributes.Add("onChange", "return txtTaxChange(this);");
            //txtCashApp.Attributes.Add("onChange", "return CashChange('" + txtCashApp.ClientID + "','" + ddlPaymentApp.ClientID + "',this);");
            //ddlPaymentApp.Attributes.Add("onChange", "return PaymentChange(this);");

        }
    }

    protected void btnCancel_Click(object sender, ImageClickEventArgs e)
    {
        appmore.deleteByApp_Id(app_id, acc_id);
        Response.Redirect("Appointment.aspx");
    }

    protected void btnExit_Click(object sender, ImageClickEventArgs e)
    {
        Response.Redirect("Appointment.aspx");
    }
    //protected void btnPayment_Click(object sender, EventArgs e)
    //{   
    //    float tips=0;
    //    if (txtTipsApp.Text == "")
    //    {
    //        tips = 0;
    //    }
    //    else
    //    {
    //        tips = float.Parse(txtTipsApp.Text);
    //        appmore.UpdateTIPS(app_id, acc_id, tips);
    //    }
    //    Response.Redirect("Appointment.aspx");
    //}
}
